/**
 * 图片压缩类
 *
 * file 需要压缩的 图片数据
 * 注意: 方法名 前带有 _ 的属于私有方法
 *  案例:
 *    var ic = new ImgCondenseClass(file)
 *   ic.imgPreview().then(res => {
 *       var image = new FormData()
        image.append('file', fileData)
 *   })
 */
class ImgCondenseClass {
  constructor(file) {
    this.file = file
  }

  // 获取图片
  imgPreview() {
    const self = this
    var file = this.file
    return new Promise((resolve, reject) => {
      // 判断支不支持FileReader
      if (!file || !window.FileReader) return
      if (/^image/.test(file.type)) {
        // 创建一个reader
        const reader = new FileReader()

        // 将图片转成base64格式
        reader.readAsDataURL(file)
        // 读取成功后的回调
        reader.onloadend = function() {
          const result = this.result
          const img = new Image()
          img.src = result
          console.log('********未压缩前的图片大小********')
          console.log(result.length)
          console.log(result)

          // 判断上传的图片是否大于 2M ,如果大于则压缩, 相反不压缩
          const isLt2M = file.size / 1024 / 1024 < 2
          if (isLt2M) {
            // 返回图片数据
            resolve(file)
          } else {
            img.onload = function() {
              const data = self._compress(img, file.size)
              const blob = self._dataURItoBlob(data)
              // blob 转file
              var fileOfBlob = new File([blob], file.name, { type: file.type })
              console.log('*******base64转blob对象******')
              console.log(blob)
              console.log(fileOfBlob)
              // 返回图片数据
              resolve(fileOfBlob)
            }
          }
        }
      }
    })
  }

  // 压缩图片
  _compress(img, fileSize) {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    // const initSize = img.src.length
    const width = img.width
    const height = img.height
    canvas.width = width
    canvas.height = height
    // 铺底色
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(img, 0, 0, width, height)

    var maxSize = 2 * 1024 * 1024 // 2M
    console.log('max:', maxSize)
    console.log('file', fileSize)
    var toSize = (maxSize / fileSize) // 压缩比例
    console.log('压缩比例')
    console.log(toSize)

    // 进行最小压缩
    const ndata = canvas.toDataURL('image/jpeg', toSize)
    return ndata
  }

  // base64转成bolb对象
  _dataURItoBlob(base64Data) {
    var byteString
    if (base64Data.split(',')[0].indexOf('base64') >= 0) { byteString = atob(base64Data.split(',')[1]) } else byteString = unescape(base64Data.split(',')[1])
    var mimeString = base64Data
      .split(',')[0]
      .split(':')[1]
      .split(';')[0]
    var ia = new Uint8Array(byteString.length)
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i)
    }
    return new Blob([ia], { type: mimeString })
  }
}

export default ImgCondenseClass
